<script setup lang="ts">
import type { Banner } from "@/types/Banner";

const props = withDefaults(
  defineProps<{
    carousels: Banner[];
    // 是否自动轮播图
    autoPlay?: boolean;
    // 自动轮播间隔时间
    duration?: number;
  }>(),
  {
    autoPlay: true,
    duration: 3000,
  }
);

// 用于记录当前显示着的轮播图的索引
let current = ref(0);
// 用于存储定时器
let timer: number | undefined | NodeJS.Timer;
// 控制轮播图索引
function toggle(step = 1): void {
  // 计算目标索引
  let nextIndex = current.value + step;
  // 如果索引范围溢出边界, 限制索引值为边界值
  // 否则索引值正常, 赋值即可
  // 左边溢出
  if (nextIndex < 0) {
    current.value = props.carousels.length - 1;
    // 右边溢出
  } else if (nextIndex > props.carousels.length - 1) {
    current.value = 0;
  } else {
    // 正常范围
    current.value = nextIndex;
  }
}

// 开始自动轮播
function startAutoPlay() {
  // 清空上一次开启的定时器
  clearInterval(timer);
  if (props.autoPlay && props.carousels.length > 1) {
    // 如果开发者设置了自动轮播并且轮播图的数量大于 1, 允许自动轮播
    timer = setInterval(toggle, props.duration);
  }
}

// 停止自动轮播
function stopAutoPlay() {
  clearInterval(timer);
}

// 组件挂载完成后 开始自动轮图
onMounted(startAutoPlay);
// 组件卸载后 清除轮播图定时器
onUnmounted(stopAutoPlay);
</script>

<template>
  <div class="xtx-carousel">
    <ul class="carousel-body">
      <li
        v-for="(item, index) in carousels"
        :key="item.nid"
        class="carousel-item"
        :class="{ fade: current === index }"
      >
        <slot :name="`default-${index}`" :current="current"></slot>
      </li>
    </ul>
  </div>
</template>

<style scoped lang="scss">
.xtx-carousel {
  position: relative;
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 720px;

  .carousel {
    &-body {
      width: 100%;
      height: 100%;
    }
    &-item {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      transition: opacity 1s linear;
      overflow: hidden;
      &.fade {
        opacity: 1;
        z-index: 1;
      }
    }
  }
}
</style>
